package com.yourenbang.lingyun.transaction.web.service.impl.pay.transaction;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.enums.ChannelIdEnums;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.constants.enums.pay.PayTypeEnum;
import com.yourenbang.lingyun.constants.enums.table.PayTransactionEnum;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.core.util.date.DateFormat;
import com.yourenbang.lingyun.core.util.date.LocalDateUtils;
import com.yourenbang.lingyun.domain.Terminal21;
import com.yourenbang.lingyun.transaction.constant.LklTransTypeEnum;
import com.yourenbang.lingyun.transaction.web.domain.dto.yxy.SftTradeDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.yxy.SftTradeExtDataDTO;
import com.yourenbang.lingyun.transaction.web.service.PayTransactionFormatService;
import com.yourenbang.terminal.api.service.RpcYxyTerminalService;
import com.yourenbang.transaction.api.model.vo.pay.PayTransaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;

/**
 * @Description 盛付通
 * @Date 2021/5/25 11:00
 * @Created by Jason
 */
@Service
@Slf4j
public class SftPayTransactionFormatServiceImpl implements PayTransactionFormatService {
    @Autowired
    private RpcYxyTerminalService rpcYxyTerminalService;
    
    @Override
    public PayTransaction payTransactionFormat(JSONObject jsonObject) {
        KLog.info("sft格式化交易推送入参:{}",jsonObject.toJSONString());

        SftTradeDTO sftTradeDTO = jsonObject.toJavaObject(SftTradeDTO.class);
        sftTradeDTO.setSftTradeExtDataDTO(JSONObject.parseObject(sftTradeDTO.getExtData(), SftTradeExtDataDTO.class));
        if(StringUtils.equals(sftTradeDTO.getTxnType(), SftTradeDTO.SFT_REFUND_TYPE)){
            log.error("盛付通退货交易,需要撤销该笔金额分润,订单号:{}",sftTradeDTO.getOrderId());
            return null;
        };

        PayTransaction payTransaction = new PayTransaction();

        payTransaction.setMerchantNo(sftTradeDTO.getSftTradeExtDataDTO().getSdpMerchant());
        payTransaction.setMerchantName(sftTradeDTO.getSftTradeExtDataDTO().getMerchantName());

        payTransaction.setRealName(sftTradeDTO.getSftTradeExtDataDTO().getMerchantName());
        payTransaction.setOrderNo(sftTradeDTO.getOrderId());
        payTransaction.setTransactionNo(sftTradeDTO.getTraceNo());
        payTransaction.setSysRef(sftTradeDTO.getTxnRef());
//        payTransaction.setSid();
//        payTransaction.setRevokeSid("");
        try {
            payTransaction.setTransactionAmount(new BigDecimal(sftTradeDTO.getAmt()).divide(new BigDecimal("100")));

        } catch (Exception e) {
            KLog.error("sft交易回调计算交易额出错:{}",sftTradeDTO.toJSON());
        }
//        payTransaction.setRate(0);
//        payTransaction.setTransactionFee(new BigDecimal("0"));
        payTransaction.setCardFlag(formatCardFlagSft(sftTradeDTO.getSftTradeExtDataDTO().getCardType(),
                sftTradeDTO.getSftTradeExtDataDTO().getIssuerCode()));
        payTransaction.setTerminalId(sftTradeDTO.getTerminalId());
//        payTransaction.setPsamNo("");
        payTransaction.setSn(sftTradeDTO.getSftTradeExtDataDTO().getSn());
        //盛付通返回为卡号后四位
        payTransaction.setTransactionCardNo(sftTradeDTO.getShortPan());
//        payTransaction.setTransactionBank("");
        payTransaction.setTransactionCardType(formatCardFlagSft(sftTradeDTO.getSftTradeExtDataDTO().getCardType(),
                sftTradeDTO.getSftTradeExtDataDTO().getIssuerCode()));
//        payTransaction.setSettlementCardNo("");
//        payTransaction.setSettlementBank("");
//        payTransaction.setSettlementCardType("");
        payTransaction.setStatus(formatTradeStatus(sftTradeDTO.getRespCode()));
        LocalDateTime transTime = LocalDateTime.now();
        if (StringUtils.isNotBlank(sftTradeDTO.getTxnTime())) {
             transTime = LocalDateUtils.stringToLocalDateTime
                    (sftTradeDTO.getTxnTime(), DateFormat.DATETIME_COMPACT.getPartten());
        }
        payTransaction.setTransactionTime(transTime);
        payTransaction.setTransactionMonth(
                LocalDateUtils.localDateTimeByFormat(transTime, DateFormat.DATE_MONTH.getPartten()));
        payTransaction.setTransactionDay(LocalDateUtils.localDateTimeByFormat(transTime, DateFormat.DATE_COMPACT.getPartten()));

//        payTransaction.setFrontSuccessTime(LocalDateTime.now());
//        payTransaction.setProvinceCode("");
//        payTransaction.setCityCode("");
//        payTransaction.setDistrictCode("");
//        payTransaction.setLongitude("");
//        payTransaction.setLatitude("");
//        payTransaction.setAreaCode("");

//        payTransaction.setWithdrawalOrderNo("");
//        payTransaction.setWithdrawalTransactionNo("");
//        payTransaction.setWithdrawalAmount(new BigDecimal("0"));
//        payTransaction.setWithdrawalFee(new BigDecimal("0"));
//        payTransaction.setFeeAmt(new BigDecimal("0"));
//        payTransaction.setAccAmt(new BigDecimal("0"));
//        payTransaction.setWithdrawalQueryTime(LocalDateTime.now());
//        payTransaction.setWithdrawalQueryCount(0);
//        payTransaction.setWithdrawalDrawTime(LocalDateTime.now());
//        payTransaction.setWithdrawalDrawCount(0);
        payTransaction.setWithdrawalStatus(PayTransactionEnum.WithdrawalStatusEnum.STATUS_40.getCode());

        Terminal21 terminal21= rpcYxyTerminalService.getTerminalBySn(payTransaction.getSn());
        if(Objects.isNull(terminal21)){
            return null;
        }
        payTransaction.setChannelId(terminal21.getChannelId());
        payTransaction.setPlatNo(PlatNoEnums.YXY.getCode());
        payTransaction.setIsDel(false);
        //交易类型从另一个接口推,第二天将前一天的押金且计入分润标识的撤销分润 更改标识为不计分润

        //分润标识
        payTransaction.setProfitFlag(checkIsProfitFlagSft(payTransaction));

        return payTransaction;
    }

    @Override
    public JSONObject dyUrlRequest(String uri, Map<String, Object> bodyJson) {
        return null;
    }

    @Override
    public JSONObject dyUrlRequestByPayType(String uri, Map<String, Object> bodyJson, PayTypeEnum payTypeEnum) {
        return null;
    }

    /**
     * 盛付通判断交易状态
     * @param respCode
     * @return
     */
    private Short formatTradeStatus(String respCode) {
        if (StringUtils.equals(respCode, "00")) {
            return PayTransactionEnum.TransactionStatus.STATUS_10.getCode();
        }
        return PayTransactionEnum.TransactionStatus.STATUS_20.getCode();
    }

    /**
     * 盛付通判断交易卡类型
     * @param cardType
     * @param issuerCode
     * @return
     */
    private String formatCardFlagSft(String cardType,String issuerCode) {
       /* cardType OA	扫码：微信，支付宝，盛付通
        CC	贷记卡
        DC	借记卡
        SCC	准贷记卡 */
        /* issuerCode
        WX	微信
        ZFB01	支付宝
        SFT01	盛付通
        CUP	银行卡
        CUP01	银联扫码支付
        CUP02	银联静态扫码支付
        CUP03	银联动态扫码支付
        NFC	碰一碰
        */
        if (StringUtils.equalsAnyIgnoreCase(cardType, "OA","")) {
            if (StringUtils.equalsIgnoreCase(issuerCode, "WX")) {
                return PayTransactionEnum.CardFlagEnum.WECHAT.getCode();
            } else if (StringUtils.equalsIgnoreCase(issuerCode, "ZFB01")) {
                return PayTransactionEnum.CardFlagEnum.ALIPAY.getCode();
            } else if(StringUtils.equalsAnyIgnoreCase(issuerCode, "CUP01","CUP02","CUP03")){
                return PayTransactionEnum.CardFlagEnum.UNIONCODE.getCode();
            }
        }
        if (StringUtils.equalsAnyIgnoreCase(cardType, "CC","SCC")) {
            return PayTransactionEnum.CardFlagEnum.CREDIT_CARD.getCode();
        }
        if (StringUtils.equalsIgnoreCase(cardType, "DC")) {
            return PayTransactionEnum.CardFlagEnum.BORROW_CARD.getCode();
        }
        return cardType;
    }

    //判断是否计入分润
    private boolean checkIsProfitFlagSft(PayTransaction payTransaction) {

        //sft押金计入分润
        if (StringUtils.equalsAny(payTransaction.getCardFlag(), PayTransactionEnum.CardFlagEnum.ALIPAY.getCode(),
                PayTransactionEnum.CardFlagEnum.WECHAT.getCode(),
                PayTransactionEnum.CardFlagEnum.CREDIT_CARD.getCode(),
                PayTransactionEnum.CardFlagEnum.UNIONCODE.getCode()) &&
                ChannelIdEnums.isEqualsAny(payTransaction.getChannelId(), ChannelIdEnums.yxy_sft_s40, ChannelIdEnums.YXY_SFT_S50)) {
            return true;
        }

        //贷记卡且非押金交易才计入分润
        if (StringUtils.equalsAny(payTransaction.getCardFlag(), PayTransactionEnum.CardFlagEnum.ALIPAY.getCode(),
                PayTransactionEnum.CardFlagEnum.WECHAT.getCode(),
                PayTransactionEnum.CardFlagEnum.CREDIT_CARD.getCode(),
                PayTransactionEnum.CardFlagEnum.UNIONCODE.getCode()) &&
                !StringUtils.equals(LklTransTypeEnum.TYPE_412001.getTransType(), payTransaction.getTransType())) {
            return true;
        }

        return false;
    }
}
